package org.example.java.nio;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.LongBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;

/**
 * Created by Juntao.Zhang on 2014/9/11.
 */
public class MappedByteBufferTest {
  public static void main(String[] args) throws Exception {
    write();
    readFile();
  }

  private static File write() throws IOException {
    File checkpointFile = new File("data/test");
    RandomAccessFile checkpointFileHandle = new RandomAccessFile(checkpointFile, "rw");
    checkpointFileHandle.writeLong(0L);
    checkpointFileHandle.writeLong(1L);
    checkpointFileHandle.getChannel().force(true);
    MappedByteBuffer mappedBuffer = checkpointFileHandle.getChannel().map(FileChannel.MapMode.READ_WRITE, 0,
        checkpointFile.length());
    LongBuffer elementsBuffer = mappedBuffer.asLongBuffer();
    elementsBuffer.put(1, 11L);
    elementsBuffer.put(0, 10L);
//    mappedBuffer.force();
    System.out.println(mappedBuffer.isLoaded());//Todo Juntao.Zhang need read deeper
    long first = elementsBuffer.get(1);
    System.out.println(first);
    checkpointFileHandle.close();
    return checkpointFile;
  }

  private static void readFile() throws IOException {
    File checkpointFile = new File("data/test");
    RandomAccessFile checkpointFileHandle;
    MappedByteBuffer mappedBuffer;
    checkpointFileHandle = new RandomAccessFile(checkpointFile, "r");
    mappedBuffer = checkpointFileHandle.getChannel().map(FileChannel.MapMode.READ_ONLY, 0,
        checkpointFile.length());
    System.out.println(mappedBuffer.asLongBuffer().get(0));
    System.out.println(mappedBuffer.asLongBuffer().get(1));
    checkpointFileHandle.close();
  }

}
